<template>
    <popup
        ref="popupRef"
        title="权限设置"
        :async="true"
        width="550px"
        @confirm="handleSubmit"
        @close="handleClose"
    >
        
        <el-form
            class="ls-form"
            ref="formRef"
            :rules="rules"
            :model="formData"
            label-width="60px"
        >
            
            <el-scrollbar class="h-[400px] sm:h-[600px]">
                <el-form-item label="权限" prop="menus">
                    <div>
                        <el-checkbox label="展开/折叠" @change="handleExpand"/>
                        <el-checkbox label="全选/不全选" @change="handleSelectAll"/>
                        
                        <div>
                            <el-tree
                                ref="treeRef"
                                :data="menuTree"
                                :props="{
                                        label: 'menuName',
                                        children: 'children'
                                    }"
                                :check-strictly="false"
                                node-key="id"
                                :default-expand-all="false"
                                show-checkbox
                            />
                        </div>
                    </div>
                
                </el-form-item>
            
            
            </el-scrollbar>
        </el-form>
    
    </popup>
</template>
<script lang="ts" setup>
import {CheckboxValueType, ElTree, FormInstance} from "element-plus";
import Popup from "@/components/popup/index.vue"
import {treeToArray} from "@/utils/util";
import feedback from "@/utils/feedback";
import {getSystemAuthMenuList} from "@/api/system/SystemAuthMenuController";
import {roleDetail, roleEdit} from "@/api/system/SystemAuthRoleController";

const treeRef = shallowRef<InstanceType<typeof ElTree>>()
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()

// 定义权限列表
const menuArray = ref<any[]>([])
// 定义权限树数据
const menuTree = ref<any[]>([])


const formData = reactive({
    id: '',
    name: '',
    remark: '',
    sort: 0,
    isDisable: 0,
    menus: [] as any[]
})


/**
 * 展开目录 节点
 * @param check
 */
function handleExpand(check: CheckboxValueType) {
    const treeList = menuTree.value
    
    // 循环调用展开
    for (let i = 0; i < treeList.length; i++) {
        //@ts-ignore
        treeRef.value.store.nodesMap[treeList[i].id].expanded = check
    }
}

const emit = defineEmits(['success', 'close'])


/**
 * 确定
 */
async function handleSubmit() {
    await formRef.value?.validate()
    // 获取当前部门
    formData.menus = getDeptAllCheckedKeys()!
    await roleEdit({...formData, menuIds: formData.menus.join()})
    
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
    
}


/**
 * 获取选择的key
 */
const getDeptAllCheckedKeys = () => {
    // 主节点
    const checkedKeys = treeRef.value?.getCheckedKeys()
    // 子节点
    const halfCheckedKeys = treeRef.value?.getHalfCheckedKeys()!
    checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys)
    return checkedKeys
}


/**
 * 取消
 */
function handleClose() {
    emit('close')
}


/**
 * 全选
 */
function handleSelectAll(check: CheckboxValueType) {
    if (check) {
        treeRef.value?.setCheckedKeys(menuArray.value.map((item) => item.id))
    } else {
        treeRef.value?.setCheckedKeys([])
    }
}


/**
 * 弹窗打开
 */
function open() {
    popupRef.value?.open()
}


/**
 *
 * 赋值
 * @param row
 */
const setFormData = async (row: Record<any, any>) => {
    // 获取菜单列表
    await getSystemAuthMenuList().then(async res => {
        menuTree.value = res
        menuArray.value = treeToArray(res)
        // 获取角色详情
        await roleDetail({id: row.id}).then(data => {
            
            for (const key in formData) {
                if (data[key] != null && data[key] != undefined) {
                    //@ts-ignore
                    formData[key] = data[key]
                }
            }
            
        })
        
    })
    
    await nextTick(() => {
        formData.menus.forEach((v) => {
            nextTick(() => {
                // 页面加载后对于当前角色的目录项目进行选中
                treeRef.value?.setChecked(v, true, false)
            })
        })
    })
    
    
}


/**
 * 权限
 */
const rules = {
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['blur']
        }
    ]
}


defineExpose({
    open,
    setFormData
})

</script>
